package org.aoao.utils;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

public class FileReadOrWrite {

    // 保存文件
    public static String saveFiles(HttpServletRequest request, @RequestParam("file1") MultipartFile file1,String fileName){
        //判断文件是否存在
        if(!file1.isEmpty()){
            try{
                // 得到项目绝对路径 / 表示是 根目录
                String path=request.getServletContext().getRealPath("/");
                File uploadFile=new File(path+"/upload");
                // 如果目录不存在，则创建
                if (!uploadFile.exists()){
                    uploadFile.mkdir();
                }
                // 得到文件名
//                String originFileName1=file1.getOriginalFilename();
                // 转存文件到指定目录
                file1.transferTo(new File(uploadFile,fileName));
                // 添加消息
                request.setAttribute("msg","上传成功！");
                return path+"/upload/"+fileName;
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("msg","上传失败！");
            }
        }else{
            request.setAttribute("msg","没有上传文件！");
        }
        return null;
    }

    public static byte[] getByteFileContent(String filePath) throws IOException {
        // 获取文件，如果文件太大，返回null
        File file=new File(filePath);
        long size=file.length();
        if (size>Integer.MAX_VALUE){
            throw new RuntimeException(filePath+" is too big!");
        }
        // 尝试将读取文件到字节数组

        FileInputStream in=new FileInputStream(file);
        byte[] buffer=new byte[(int) size];
        int offset=0, readNum=0;
        while (offset<size &&
                (readNum=in.read(buffer,offset, (int) size-offset))>=0){
            offset+=readNum;
        }
        // 确保所有数据被读取
        if (offset!= buffer.length){
            throw new IOException("未能完全读取文件 "+filePath);
        }
        in.close();
        return buffer;
    }
    public static String getStringFileContent(String filePath) throws IOException {
        // 获取文件，如果文件太大，返回null
        BufferedReader bufferedReader=new BufferedReader(new FileReader(filePath));
        // 存放
        StringBuilder stringBuilder=new StringBuilder();
        // 存放每行
        String readLine=bufferedReader.readLine();
        while((readLine=bufferedReader.readLine())!=null){
            stringBuilder.append(readLine);
        }
        return stringBuilder.toString();
    }
    // 使用 读取doc文件的jar包工具 读取指定doc文件，并以字符串形式返回
    public static String getDocString(String path){
        String buffer = "";
        try {
            if (path.endsWith(".doc")) {
                FileInputStream is = new FileInputStream(path);
                WordExtractor ex = new WordExtractor(is);
                buffer = ex.getText();
                is.close();
            } else if (path.endsWith("docx")) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                buffer = extractor.getText();
                opcPackage.close();
            } else {
                System.out.println("此文件不是word文件！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }
}
